package com.iot.modbus.manager;


import com.iot.modbus.builder.WriterSessionFactoryBuilder;
import com.iot.modbus.factory.WriterSessionFactory;
import com.iot.modbus.reader.ReaderSession;
import com.iot.modbus.writer.WriterSession;
import com.serotonin.modbus4j.ip.IpParameters;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class WriterSessionManager {
    private static final Map<String, WriterSession> sessionMap = new ConcurrentHashMap<>();

    private static final WriterSessionFactoryBuilder writerSessionFactoryBuilder = new WriterSessionFactoryBuilder();

    private static final WriterSessionFactory writerSessionFactory = writerSessionFactoryBuilder.build();

    private static String getKey(final IpParameters ipParameters) {
        return ipParameters.getHost() + "<>" + ipParameters.getPort();
    }


    public static WriterSession add(IpParameters ipParameters) {
        WriterSession writerSession = writerSessionFactory.createWriterSession(ipParameters);;
        sessionMap.put(getKey(ipParameters), writerSession);
        return writerSession;
    }

    public static WriterSession remove(IpParameters ipParameters) {
        return sessionMap.remove(getKey(ipParameters));
    }

    public static WriterSession get(IpParameters ipParameters) {
        if (!sessionMap.containsKey(getKey(ipParameters))) {
            return add(ipParameters);
        }
        return sessionMap.get(getKey(ipParameters));
    }

}
